package org.wanda.pv.controller.hy;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.framework.utils.StringUtil;

import org.wanda.pv.model.hy.*;
import org.wanda.pv.model.user.SysUser;
import org.wanda.pv.service.user.HyUserInfoService;
import org.wanda.pv.util.HyUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lxy
 */

@RestController
@RequestMapping("/hy")
public class HyController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Value("${wanda_pv.redirectUrl}")
    private  String  redirectUrl;

    @Autowired
    private HyUserInfoService hyUserInfoService;

    @Autowired
    private Dao dao;


    @RequestMapping("/forwardTo_pv")
    public ModelAndView forwardTo_pv(HttpServletRequest request,String access_token_hy,String projectFlowChildrenNodeId,String projectId){
        ModelAndView mv = new ModelAndView("redirect:"+redirectUrl+"?access_token_hy="+access_token_hy+"&projectFlowChildrenNodeId="+projectFlowChildrenNodeId+"&projectId="+projectId);
        System.out.println(redirectUrl+"?access_token_hy="+access_token_hy+"&projectFlowChildrenNodeId="+projectFlowChildrenNodeId+"&projectId="+projectId);
        return mv;
    }




    @RequestMapping("/approve")

    public ModelAndView approve (HttpServletRequest request,int count){
        String access_token = (String)request.getSession().getAttribute("access_token");
        String projectFlowChildrenNodeId = (String)request.getSession().getAttribute("projectFlowChildrenNodeId");
        projectFlowChildrenNodeId=StringUtil.isEmpty(projectFlowChildrenNodeId)?"514092b28d8143e5aae2fafb953e0852":projectFlowChildrenNodeId;


        HyToken hyToken = HyUtil.getHyToken();
        access_token=StringUtil.isEmpty(access_token)?hyToken.getAccess_token():access_token;


        System.out.println("count:::"+count);
        HyUtil.sendWS(access_token,projectFlowChildrenNodeId,count);


        ModelAndView mv = new ModelAndView("redirect:http://47.94.13.146");


        return mv;


    }


    @RequestMapping("/nodeInfo")
    public Object nodeInfo(HttpServletRequest request,String id){

        try{
            String access_token = (String)request.getSession().getAttribute("access_token");
            String projectFlowChildrenNodeId = (String)request.getSession().getAttribute("projectFlowChildrenNodeId");
            projectFlowChildrenNodeId=StringUtil.isEmpty(projectFlowChildrenNodeId)?"40bb06b765144d0cbbdc314dc540d0dd":projectFlowChildrenNodeId;
            access_token=StringUtil.isEmpty(access_token)?HyUtil.getHyToken().getAccess_token():access_token;

            List<HyDrawing> nodeInfo = HyUtil.getDrawings(access_token, projectFlowChildrenNodeId, id);

            return Result.success("success",nodeInfo);
        }catch (Exception e){
            log.error(e.getMessage(),e);

            return Result.error("fail","服务器内部错误");
        }

    }


    @RequestMapping("/getTree")
    public Object getTree(HttpServletRequest request){
        try{
            String access_token = (String)request.getSession().getAttribute("access_token");
            if (StringUtil.isEmpty(access_token)){
                access_token = HyUtil.getHyToken().getAccess_token();
            }
            List<HyTree> tree = HyUtil.getTree(access_token);
            return Result.success("success",tree.get(0));

        }catch (Exception e){
            log.error(e.getMessage(),e);

            return Result.error("fail","服务器内部错误");

        }



    }


    @RequestMapping("/setSession")
    public  Object setSession(HttpServletRequest request,String access_token_hy,String projectFlowChildrenNodeId,String projectId){
        log.debug("projectId ::::>>>>" +projectId);

        Map<String,Object> map=new HashMap<>();
        request.getSession().setAttribute("access_token",access_token_hy);
        request.getSession().setAttribute("projectFlowChildrenNodeId",projectFlowChildrenNodeId);
        request.getSession().setAttribute("projectId",projectId);
        String id=HyUtil.getUserSimple(access_token_hy);
        Map<String,Object> resultMap = (Map<String, Object>) HyUtil.checkTokenStatus(id,access_token_hy);
        boolean status= (boolean) resultMap.get("status");
        if ( status == false){
            String msg= (String) resultMap.get("msg");
            return Result.error(msg,msg);
        }
        //先去数据库查询用户存不存在,如果符合条件。说明 项目存在，用户存在，企业存在
        HyUserInfo hyUserInfoData=  dao.fetch(HyUserInfo.class,Cnd.where("hyUserId","=",id).and("hyProjectInfoId","=",projectId));
        if(hyUserInfoData == null){
            map.put("firstLogin",true);
            log.debug("firstLogin: >>>>>>>>>>"+true);
            //获取用户信息
            hyUserInfoData= HyUtil.getUserInfo(id,access_token_hy);
            //获取角色
            HyRole hyRole = HyUtil.getprojectRoleList(access_token_hy,projectId,hyUserInfoData.getHyUserId());
            HyRole hyRoleData = dao.fetch(HyRole.class,Cnd.where("id","=",hyRole.getId()));
            if (hyRoleData == null){
                hyRole = dao.insert(hyRole);
            }
            hyUserInfoData.setHyRole(hyRole);
            HyOffice hyOfficeData=dao.fetch(HyOffice.class, Cnd.where("id","=",hyUserInfoData.getHyOfficeId()));
            if(hyOfficeData == null){
                HyOffice hyOffice=hyUserInfoData.getHyOffice();
                dao.insert(hyOffice);
            }
            hyUserInfoData.setHyRoleId(hyRole.getId());
            hyUserInfoData.setHyRole(hyRole);
            hyUserInfoData.setHyProjectInfoId(projectId);
            dao.insert(hyUserInfoData);
            request.getSession().setAttribute("userInfo",hyUserInfoData);
        }else{
            //如果存在，就把数据库的信息放到 session
            log.debug("firstLogin: >>>>>>>>>>"+false);

            map.put("firstLogin",false);
            dao.fetchLinks(hyUserInfoData,null);
            request.getSession().setAttribute("userInfo",hyUserInfoData);

        }
        //判断项目存不存在
        HyProjectInfo hyProjectInfo = dao.fetch(HyProjectInfo.class,Cnd.where("id","=",projectId));
        if(hyProjectInfo == null){
            hyProjectInfo = HyUtil.getProjectInfo(projectId,access_token_hy);
            hyProjectInfo.setStatus(0);
            dao.insert(hyProjectInfo);
        }else{
            if(hyProjectInfo.getStatus() != 1 ){
                hyProjectInfo.setStatus(0);
                dao.update(hyProjectInfo);
            }
        }
        hyUserInfoData.setHyProjectInfo(hyProjectInfo);
       //如果项目状态为正在初始化，就跳过初始化方法，继续等待响应,只有等待初始化方法，才走初始化
        if(hyProjectInfo.getStatus() == 0 ){
            hyProjectInfo.setStatus(1);
            dao.update(hyProjectInfo);
            hyUserInfoService.initUserDrawing(hyUserInfoData,access_token_hy,projectFlowChildrenNodeId,projectId);
        }
        map.put("userInfo",hyUserInfoData);
        return Result.success("success",map);
    }


    @RequestMapping("/forward_pv")
    public ModelAndView forward_pv(HttpServletRequest request,String access_token_hy,String projectFlowChildrenNodeId,String access_token){
        request.getSession().setAttribute("access_token_hy",access_token_hy);
        request.getSession().setAttribute("projectFlowChildrenNodeId",projectFlowChildrenNodeId);
       String url = "http://localhost:8001/wanda_pv/#/drawing?access_token_hy="+access_token_hy+"&projectFlowChildrenNodeId="+projectFlowChildrenNodeId;
        ModelAndView mv = new ModelAndView("redirect:"+url);
        return mv;
    }

    @RequestMapping("/getSession")
    public Object test2(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        String access_token = (String) request.getSession().getAttribute("access_token");
        String projectFlowChildrenNodeId = (String) request.getSession().getAttribute("projectFlowChildrenNodeId");
        HyUserInfo hyUserInfo= (HyUserInfo) request.getSession().getAttribute("userInfo");
        String projectId= (String) request.getSession().getAttribute("projectId");
        result.put("access_token",access_token);
        result.put("projectFlowChildrenNodeId",projectFlowChildrenNodeId);
        result.put("projectId",projectId);
        result.put("userInfo", hyUserInfo);
        return Result.success("success",result);
    }

    @RequestMapping("/WdHome")
    public Object getToken(){
        HyToken hyToken =HyUtil.getHyToken();
        ModelAndView mv = new ModelAndView("redirect:"+redirectUrl+"?access_token_hy="+hyToken.getAccess_token()+"&projectFlowChildrenNodeId="+"1e4759d4756143c990d50ced64295fe4"+"&projectId="+"51C6E0C9-6BB6-4DDC-8D16-298B398C2805");
        return mv;
    }

    @RequestMapping("/DeHome")
    public Object getSJToken(){
        HyToken hyToken =HyUtil.getHyTokenByUser("设计总包WS ","UhezYp1frc/DEMfYNkgUPg==");
        ModelAndView mv = new ModelAndView("redirect:"+redirectUrl+"?access_token_hy="+hyToken.getAccess_token()+"&projectFlowChildrenNodeId="+"1e4759d4756143c990d50ced64295fe4"+"&projectId="+"51C6E0C9-6BB6-4DDC-8D16-298B398C2805");
        return mv;
    }
    @RequestMapping("/PvHome")
    public Object getSSToken(){
        HyToken hyToken =HyUtil.getHyTokenByUser("三审单位WS","UhezYp1frc/DEMfYNkgUPg==");
        ModelAndView mv = new ModelAndView("redirect:"+redirectUrl+"?access_token_hy="+hyToken.getAccess_token()+"&projectFlowChildrenNodeId="+"cba8c9b5f04a4fc2ac39475b5e3806fe"+"&projectId="+"51C6E0C9-6BB6-4DDC-8D16-298B398C2805");
        return mv;
    }
    @RequestMapping("/NewHome")
    public Object getSsSToken(){
        HyToken hyToken =HyUtil.getHyTokenByUser("项目公司X","UhezYp1frc/DEMfYNkgUPg==");
        ModelAndView mv = new ModelAndView("redirect:"+redirectUrl+"?access_token_hy="+hyToken.getAccess_token()+"&projectFlowChildrenNodeId="+"1e4759d4756143c990d50ced64295fe4"+"&projectId="+"6BFB4A44-C634-42B2-96F2-A6A32E59A712");
        return mv;
    }


    @RequestMapping("/WdHome1")
    public Object getTokenss(){
        HyToken hyToken =HyUtil.getHyToken();
        ModelAndView mv = new ModelAndView("redirect:"+redirectUrl+"?access_token_hy="+hyToken.getAccess_token()+"&projectFlowChildrenNodeId="+"1e4759d4756143c990d50ced64295fe4"+"&projectId="+"6BFB4A44-C634-42B2-96F2-A6A32E59A712");
        return mv;
    }

}
















































/**
 *
 * @RequestMapping("/opinionCount")

public Object opinionCount(){
Map<String,Object> result  = new HashMap<>();
int random = (int) (1 + Math.random() * (100));
if (random%2==0){
result.put("opinionCount",0);
}
result.put("opinionCount",random);
return Result.success("success",result);
}

public  Object opinionCount1(HttpServletRequest request,String access_token_hy,String projectFlowChildrenNodeId){
List<HyTree> hyTrees = HyUtil.getTree(access_token_hy);
//access_token_hy = (String)request.getSession().getAttribute("access_token");
//String projectFlowChildrenNodeId = (String)request.getSession().getAttribute("projectFlowChildrenNodeId");
projectFlowChildrenNodeId=StringUtil.isEmpty(projectFlowChildrenNodeId)?"40bb06b765144d0cbbdc314dc540d0dd":projectFlowChildrenNodeId;
access_token_hy=StringUtil.isEmpty(access_token_hy)?HyUtil.getHyToken().getAccess_token():access_token_hy;
List<HyDrawing> hyDrawings = dao.query(HyDrawing.class, Cnd.where("projectFlowChildrenNodeId", "=", projectFlowChildrenNodeId));
if(hyDrawings.size()>0){
hyTrees = changeOptionCount(hyDrawings, access_token_hy,projectFlowChildrenNodeId);

}


return hyTrees;
}

private List<HyTree> changeOptionCount(List<HyDrawing> hyDrawings,String access_token,String projectFlowChildrenNodeId) {
List<String> flowMapModelIds = hyDrawings.stream().map(item -> item.getFlowMapModelId()).collect(Collectors.toList());

if (StringUtil.isEmpty(access_token)){
access_token = HyUtil.getHyToken().getAccess_token();
}
List<HyTree> tree = HyUtil.getTree(access_token);

for (String flowMapModelId: flowMapModelIds){
changeOptionCount_(tree,flowMapModelId,projectFlowChildrenNodeId);

}




return tree;

}

private void changeOptionCount_(List<HyTree> tree, String flowMapModelId,String projectFlowChildrenNodeId) {

for (HyTree hyTree:tree){

System.out.println("hyTree.getId() :::: "+hyTree.getId());
System.out.println("flowMapModelId :::: "+flowMapModelId);
if (hyTree.getId().equals(flowMapModelId)){
// 获取树节点下的问题总数
int opinionCount = getOpinionCount(flowMapModelId, projectFlowChildrenNodeId);
System.out.println("opinionCount :::: "+opinionCount);
hyTree.setOpinionCount(opinionCount);
return;
}else if(hyTree.getChildren().size()>0){
changeOptionCount_(hyTree.getChildren(),flowMapModelId,projectFlowChildrenNodeId);
}
}

}

private int getOpinionCount(String flowMapModelId, String projectFlowChildrenNodeId) {

List<HyDrawing> hyDrawings = dao.query(HyDrawing.class, Cnd.where("projectFlowChildrenNodeId", "=", projectFlowChildrenNodeId).and("flowMapModelId", "=", flowMapModelId));

int count = 0;
if (hyDrawings.size()>0){
count= hyDrawings.stream().mapToInt(item->item.getOpinionCount()).sum();
}

return count;
}

 * **/